package com.bosssoft.setp.handler;


import com.bosssoft.setp.constant.CommonConstant;
import com.bosssoft.setp.model.business.course.CourseType;
import org.springframework.stereotype.Service;
import xyz.erupt.annotation.fun.DataProxy;
import xyz.erupt.core.exception.EruptApiErrorTip;
import xyz.erupt.jpa.dao.EruptDao;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 课程类别数据代理
 *
 * @author clt
 */
@Service
public class CourseTypeDataProxy implements DataProxy<CourseType> {
    @Resource
    private EruptDao eruptDao;

    private String sql = "SELECT level FROM setp_course_type WHERE id = ?";

    private String sqlForSubCourse = "SELECT COUNT(id) FROM setp_course WHERE course_type_id = ?";

    /**
     * 添加前操作
     * @param courseType
     */
    @Override
    public void beforeAdd(CourseType courseType) {

        /**
         * 设置层级级别
         */
       Long parentId = courseType.getParentId();
       Integer level = null;
       if(parentId == null){
           level = 0;
       }else{
           Integer parentLevel = eruptDao.getJdbcTemplate().queryForObject(sql.replace("?",parentId.toString()),Integer.class);
           level = parentLevel + 1;
       }

       courseType.setLevel(level);

        /**
         * 生成编号
         */
       if(parentId == null){
           Integer maxCode = eruptDao.getJdbcTemplate().queryForObject("SELECT MAX(code) FROM setp_course_type WHERE level = 0",Integer.class);
           if(maxCode == null){
               maxCode = 0;
           }
           courseType.setCode(String.format("%03d",maxCode + 1));
       }else {
           String parentCode = eruptDao.getJdbcTemplate().queryForObject("SELECT code FROM setp_course_type WHERE id = ?",String.class,parentId);
           String maxcode = eruptDao.getJdbcTemplate().queryForObject("SELECT MAX(code) FROM setp_course_type WHERE parent_id = ?", String.class, courseType.getParentId());
           if(maxcode == null){
               maxcode = CommonConstant.DEFALT_CODE;
           }else {
               maxcode = maxcode.substring(maxcode.lastIndexOf(CommonConstant.COMMA) + 1);
               maxcode = String.format("%03d",Integer.parseInt(maxcode) + 1);
           }

           courseType.setCode(parentCode + CommonConstant.COMMA + maxcode);
       }

    }

    /**
     * 更新前操作
     * @param courseType
     */
    @Override
    public void beforeUpdate(CourseType courseType) {
        Long parentId = courseType.getParentId();
        Integer level = null;
        if(parentId == null){
            level = 0;
        }else{
            Integer parentLevel = eruptDao.getJdbcTemplate().queryForObject(sql.replace("?",parentId.toString()),Integer.class);
            level = parentLevel + 1;
        }

        courseType.setLevel(level);


        /**
         * 更新子类别编码
         */
        if(parentId == null){
            List<Map<String, Object>> results = eruptDao.getJdbcTemplate().queryForList(
                    "SELECT id, code FROM setp_course_type WHERE level = ?", 0);

            Map<Object, String> courseTypes = new HashMap<>();
            for (Map<String, Object> row : results) {
                courseTypes.put(row.get("id"), (String) row.get("code"));
            }

            for (Object id : courseTypes.keySet()){
                String oldCode = courseTypes.get(id);
                String lastPart = oldCode.substring(oldCode.lastIndexOf(CommonConstant.COMMA) + 1);
                String newCode = String.format("%03d",Integer.parseInt(lastPart) + 1);
                eruptDao.getJdbcTemplate().update("UPDATE setp_course_type SET code = ? WHERE id = ?", new Object[]{newCode, id});
            }
        }else {
            String parentCode = eruptDao.getJdbcTemplate().queryForObject("SELECT code FROM setp_course_type WHERE id = ?",String.class,parentId);

            boolean isPrefix = courseType.getCode().startsWith(parentCode);
            if(!isPrefix){
                throw new EruptApiErrorTip("课程类别编码必须以父类别编码开头");
            }

            List<Map<String, Object>> results = eruptDao.getJdbcTemplate().queryForList(
                    "SELECT id, code FROM setp_course_type WHERE parent_id = ?", parentId);

            Map<Object, String> courseTypes = new HashMap<>();
            for (Map<String, Object> row : results) {
                courseTypes.put(row.get("id"), (String) row.get("code"));
            }

            for (Object id : courseTypes.keySet()){
                String oldCode = courseTypes.get(id);
                String lastPart = oldCode.substring(oldCode.lastIndexOf(CommonConstant.COMMA) + 1);
                String newCode = parentCode + CommonConstant.COMMA + String.format("%03d",Integer.parseInt(lastPart) + 1);
                eruptDao.getJdbcTemplate().update("UPDATE setp_course_type SET code = ? WHERE id = ?", new Object[]{newCode, id});
            }
        }
    }

    /**
     * 删除前操作
     * @param courseType
     */
    @Override
    public void beforeDelete(CourseType courseType) {
        Integer count = eruptDao.getJdbcTemplate().queryForObject(
                sqlForSubCourse,
                new Object[]{courseType.getId()},
                Integer.class
        );

        if (count != null && count > 0){
            throw new EruptApiErrorTip("该课程类别下有课程，不可删除");
        }
    }

    @Override
    public void afterDelete(CourseType courseType) {
        String sql = "DELETE FROM setp_course_select WHERE course_type_id =?";
        eruptDao.getJdbcTemplate().update(sql, courseType.getId());
    }

    @Override
    public void afterUpdate(CourseType courseType) {

        if (courseType.getParentId()!= null) {
            String sql = "UPDATE setp_course_select SET name =? , parent_id =? WHERE course_type_id = ?";
            String sql2 = "SELECT id FROM setp_course_select WHERE name = ? ";
            Long matchId = eruptDao.getJdbcTemplate().queryForObject(
                    sql2, Long.class, courseType.getParentName());
            int rowsAffected = eruptDao.getJdbcTemplate().update(sql, courseType.getName(), matchId,courseType.getId());

        } else {
            String sql = "UPDATE setp_course_select SET name =? WHERE course_type_id = ?";

            int rowsAffected = eruptDao.getJdbcTemplate().update(sql, courseType.getName(), courseType.getId());
        }

    }

    @Override
    public void afterAdd(CourseType courseType) {
        /**
         * 把类型添加到课程选择表中
         */
        if (courseType.getParentId()!= null) {
            String sql = "INSERT INTO setp_course_select (name,is_course,parent_id,course_type_id) VALUES (?, ?, ?,?)";

            String sql2 = "SELECT id FROM setp_course_select WHERE name = ? ";
            Long matchId = eruptDao.getJdbcTemplate().queryForObject(
                    sql2, Long.class, courseType.getParentName());
            int rowsAffected = eruptDao.getJdbcTemplate().update(sql, courseType.getName(),false,matchId ,courseType.getId()  );

        }else {
            String sql = "INSERT INTO setp_course_select (name,is_course,course_type_id) VALUES (?, ?,?)";
            int rowsAffected = eruptDao.getJdbcTemplate().update(sql, courseType.getName(),false, courseType.getId()  );

        }

    }



}